package com.liu.qqserver.server;
import com.liu.qqcommon.Message;
import com.liu.qqcommon.MessageType;
import com.liu.qqcommon.User;
import com.sun.org.apache.bcel.internal.generic.ANEWARRAY;

import javax.jws.Oneway;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 这是服务端，监听9999端口,等待客户端的连接并保持通讯
 */
public class QQServer {

    private ServerSocket ss =null;

    //创建集合，可以保存多用户的id和pws
    private static ConcurrentHashMap<String, User> validUsers = new ConcurrentHashMap<>();
    static{//静态代码块，初始化一次validUsers
        validUsers.put("100",new User("100","123456"));
        validUsers.put("200",new User("200","123456"));
        validUsers.put("300",new User("300","123456"));
        validUsers.put("至尊宝",new User("至尊宝","123456"));
        validUsers.put("紫霞仙子",new User("紫霞仙子","123456"));
        validUsers.put("菩提老祖",new User("菩提老祖","123456"));

    }

    //验证用户是否有效的方法
    public boolean checkUser(String userId,String password){
        User user = validUsers.get(userId);
        if(user == null){//说明userId不存在
            return false;
        }
        if(!user.getPassword().equals(password)){//userId正确，pws错误
            return false;
        }
        return true;
    }
    public QQServer() {
        System.out.println("服务端在9999端口监听");
        //端口可以写在配置文件中
        try {
            ss = new ServerSocket(9999);
            //启动推送
            new Thread(new SendNewsToAllService()).start();
            //一直在循环监听，将所有客户端都监听
            while(true) {
                Socket socket = ss.accept();
                //得到Socket输入关联的对象
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                //得到Socket输出关联的对象
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                User u= (User) ois.readObject();//读取客户端发送的User对象
                //创建一个Message对象，回复客户端
                Message message = new Message();
                //合法用户
                if(checkUser(u.getUserId(),u.getPassword())) {
                    message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    //将message消息回复
                    oos.writeObject(message);
                    //创建一个线程和客户端保持通讯，该线程需要持有Socket对象
                    ServerConnectClientThread scct = new ServerConnectClientThread(socket, u.getUserId());
                    scct.start();
                    //把该线程对象放入集合中，进行管理
                    ManageServerThreads.addClientThreads(u.getUserId(), scct);

                }else {//登录失败
                    message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
                    oos.writeObject(message);
                    socket.close();
                }

            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally{
            //如果服务端退出while循环，说明服务端退出监听
            try {
                ss.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
